﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// ChangeInfoHandler 的摘要说明
    /// </summary>
    public class ChangeInfoHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            GetParams(context);
        }
        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams(HttpContext context)
        {
            string areaCode = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["areaCode"]))
            {
                areaCode = context.Request.Params["areaCode"];
            }
            ////异步调用方法
            if (context.Request.Params["action"] != null)
            {
                string action = context.Request.Params["action"].Trim();
                switch (action)
                {
                    case "DDlChangeItem":
                        BindDDlChangeItem(context);
                        break;
                    case "FindOldValue":
                        FindOldValueBySelectItem(context, areaCode);
                        break;
                    case "ChangeControl":
                        GetSubChangeControl(context, areaCode);
                        break;
                    case "ChangeItem":
                        GetChangeItemList(context);
                        break;
                    case "ChangeItemDel":
                        GetChangeItemDel(context);
                        break;
                    case "ChangeSetAdd":
                        ChangeSetSave(context, areaCode, true);
                        break;
                    case "ChangeSetEdit":
                        ChangeSetSave(context, areaCode, false);
                        break;
                    case "ChangeSet":
                        ChangeSetSubmit(context, areaCode);
                        break;
                    case "ChangeSetInfo":
                        GetChangeInfo(context, areaCode);
                        break;
                    case "ChangeAudit":
                        ChangeAudit(context, areaCode);
                        break;

                }
            }
        }

        #region 绑定变更事项
        /// <summary>
        /// 绑定信息变更项
        /// </summary>
        private void BindDDlChangeItem(HttpContext context)
        {
            string changeType = string.Empty;
            string changeItems = string.Empty;
            string areaCode = string.Empty;
            string currentArea = string.Empty;
            int appId = 0;
            if (context.Request.Params["changeType"] != null)
            {
                changeType = context.Request.Params["changeType"].ToString();
            }
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"].Trim();
            }
            if (context.Request.Params["CurrentArea"] != null)
            {
                currentArea = context.Request.Params["CurrentArea"].Trim();
            }
            if (context.Request.Params["appId"] != null)
            {
                int.TryParse(context.Request.Params["appId"].Trim(),out appId);
            }
            if (changeType == "Corp")
            {
                changeItems = "Corp,Safe";
                if (areaCode != currentArea)//外地企业
                {
                    changeItems = "Corp,Safe,CorpWdrq";
                }
            }
            else if (changeType == "Person")
            {
                changeItems = "Person,PersonQualityB";
            }
            else
            {
                changeItems = changeType;
                //changeItems = Enum.GetName(typeof(ChangeTypeEnum), ChangeType);
            }
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                OutputData(client.GetChangeItems(changeItems,appId.ToString(), currentArea));
            }
        }
        /// <summary>
        /// 取得变更前数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="selectColumn"></param>
        private void FindOldValueBySelectItem(HttpContext context, string areaCode)
        {
            string selectColumn = string.Empty;
            string objectId = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["selValue"]))
            {
                selectColumn = context.Request.Params["selValue"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["objectId"]))
            {
                objectId = context.Request.Params["objectId"];
            }
            if (string.IsNullOrEmpty(selectColumn) || selectColumn.Equals("-1"))
            {
                OutputData("{\"result\":1,\"message\":\"参数错误！\"}");
                return;
            }
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                string result1 = client.GetBeforeChangeValue(selectColumn, areaCode, new string[] { objectId });
                string key = string.Empty;
                string value = string.Empty;
                if (result1 != null)
                {
                    Dictionary<string, string> result = JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetBeforeChangeValue(selectColumn, areaCode, new string[] { objectId }));
                    if (!string.IsNullOrEmpty(result.Keys.First()) && !string.IsNullOrEmpty(result.Values.First()))
                    {
                        key = result.Keys.First().Length <= 1000 ? result.Keys.First() : result.Keys.First().Substring(0, 1000);
                        value = result.Values.First().Length <= 1000 ? result.Values.First() : result.Values.First().Substring(0, 1000);
                    }
                }
                string result2 = "{\"result\":0,\"key\":\"" + key + "\",\"value\":\"" + value + "\"}";
                OutputData(result2);
            }
        }
        /// <summary>
        /// 取得变更后待选下拉列表绑定数据源
        /// </summary>
        /// <param name="context"></param>
        /// <param name="areaCode"></param>
        private void GetSubChangeControl(HttpContext context, string areaCode)
        {
            string selectValue = string.Empty;
            //string id = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["selValue"]))
            {
                selectValue = context.Request.Params["selValue"];
            }
            //if (!string.IsNullOrEmpty(context.Request.Params["id"]))
            //{
            //    id = context.Request.Params["id"];
            //}
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                OutputData(client.GetBindChangeValue(selectValue, areaCode, null));
            }
        }

        #endregion

        #region 变更项列表操作
        /// <summary>
        /// 取得变更项列表
        /// </summary>
        /// <param name="context"></param>
        private void GetChangeItemList(HttpContext context)
        {
            string item = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["item"]))
            {
                item = context.Request.Params["item"].Trim();
            }
            if (context.Request.Params["data"] == null)
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            string data = context.Request.Params["data"];//取得客户端提交的数据
            var itemInfo = JsonConvert.DeserializeObject<Utilities.JsonEntity>(context.Request.Params["data"]);
            if (itemInfo != null && !string.IsNullOrEmpty(itemInfo.value))
            {
                //对象值为json格式的对象实体，转化实体对象
                var changeItem = JsonConvert.DeserializeObject<ModelService.Tb_ChangeRecord>(itemInfo.value.Trim('\"'));
                changeItem.OptDate = DateTime.Now;
                List<ModelService.Tb_ChangeRecord> list = new List<Tb_ChangeRecord>();
                //取得变更项列表数据
                if (!string.IsNullOrEmpty(item))
                {
                    list = JsonConvert.DeserializeObject<List<ModelService.Tb_ChangeRecord>>(item);
                }
                //添加变更项返回列表
                list.Add(changeItem);
                item = JsonConvert.SerializeObject(list);
            }
            OutputData("{\"Result\":true,\"Message\":\"操作成功！\",\"list\":" + item + "}");
            // OutputData(item);
        }

        /// <summary>
        /// 客户端删除变更项
        /// </summary>
        /// <param name="context"></param>
        private void GetChangeItemDel(HttpContext context)
        {
            string item = string.Empty;
            int tmpId = 0;
            if (string.IsNullOrEmpty(context.Request.Params["item"]))
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            if (!string.IsNullOrEmpty(context.Request.Params["tmpId"]))
            {
                int.TryParse(context.Request.Params["tmpId"].Trim(), out tmpId);
            }
            item = context.Request.Params["item"].Trim();//取得变更项列表数据
            List<ModelService.Tb_ChangeRecord> list = JsonConvert.DeserializeObject<List<ModelService.Tb_ChangeRecord>>(item);
            if (tmpId < 0 || list == null || list.Count < (tmpId + 1))
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            list.RemoveAt(tmpId);//删除变更项
            item = JsonConvert.SerializeObject(list);
            OutputData("{\"Result\":true,\"list\":" + item + "}");
            // OutputData(item);
        }

        #endregion

        #region 变更集操作
        /// <summary>
        /// 取得变更集信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        private void GetChangeInfo(HttpContext context, string areaCode)
        {
            string changeType = string.Empty;
            int setId = 0;
            if (context.Request.Params["setId"] != null)
            {
                int.TryParse(context.Request.Params["setId"].ToString(), out setId);
            }
            if (context.Request.Params["changeType"] != null)
            {
                changeType = context.Request.Params["changeType"].ToString();
            }
            if (setId == 0)
            {
                var result1 = "{\"result\":1,\"message\":\"参数错误！\"}";
                OutputData(result1);
                return;
            }
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                var result = JsonConvert.DeserializeObject<ModelService.ChangeDetail>(client.GetChangeDetails(changeType, setId, areaCode));
                var changeSet = result.ChangeSet;
                var changInfo = result.ChangeInfos;
                var result2 = "{\"result\":0,\"changInfo\":" + JsonConvert.SerializeObject(changInfo) + ",\"changeSet\":" + JsonConvert.SerializeObject(changeSet) + "}";
                OutputData(result2);

            }
        }
        /// <summary>
        /// 添加修改变更集信息
        /// </summary>
        private void ChangeSetSave(HttpContext context, string areaCode, bool flag)
        {
            if (context.Request.Params["data"] == null || string.IsNullOrEmpty(context.Request.Params["item"]))
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            //验证图片是否上传
            string result = CheckImgFile(context);
            if (!string.IsNullOrEmpty(result))
            {
                OutputData("{\"Result\":false,\"Message\":\"img\",\"ReturnValue\":\"" + result + "\"}");
                return;
            }
            string item = context.Request.Params["item"].Trim();//变更项列表
            string data = context.Request.Params["data"];//变更集
            //对象值为json格式的对象实体，转化实体对象
            List<ModelService.Tb_ChangeRecord> list = JsonConvert.DeserializeObject<List<ModelService.Tb_ChangeRecord>>(item);
            var dataInfo = JsonConvert.DeserializeObject<Utilities.JsonEntity>(context.Request.Params["data"]);
            //对象值为json格式的对象实体，转化实体对象
            var changeSet = JsonConvert.DeserializeObject<ModelService.Tb_ChangeSetRecord>(dataInfo.value.Trim('\"'));
            changeSet.AppId =System.Configuration.ConfigurationManager.AppSettings["AppID"];
            changeSet.IsrtDate = DateTime.Now;
            changeSet.IsDel = false;
            
            if (changeSet == null || string.IsNullOrEmpty(changeSet.Description) || list == null || list.Count == 0)
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            string corpGuid = string.Empty;
            string userName = string.Empty;
            string roleId = string.Empty;
            string changeType = string.Empty;
            if (context.Request.Params["corpGuid"] != null)
            {
                corpGuid = context.Request.Params["corpGuid"].ToString();
            }
            if (context.Request.Params["userName"] != null)
            {
                userName = context.Request.Params["userName"].ToString();
            }
            if (context.Request.Params["roleId"] != null)
            {
                roleId = context.Request.Params["roleId"].ToString();
            }
            if (context.Request.Params["changeType"] != null)
            {
                changeType = context.Request.Params["changeType"].ToString();
            }
            if (context.Request.Params["IsrtDate"] != null)
            {
                DateTime IsrtDate = DateTime.Now;
               if (DateTime.TryParse(context.Request.Params["IsrtDate"].ToString(),out IsrtDate))
                {
                    changeSet.IsrtDate = IsrtDate;
                }
            }
            //执行添加修改事件
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
                if (flag)
                {
                    result = client.AddChange(JsonConvert.SerializeObject(changeSet), JsonConvert.SerializeObject(list), changeType, corpGuid, roleId, userName, areaCode);
                }
                else
                {
                    result = client.EditChange(JsonConvert.SerializeObject(changeSet), JsonConvert.SerializeObject(list), changeType, corpGuid, roleId, userName, areaCode);
                }
                OutputData(result);
            }
        }
        /// <summary>
        /// 上报变更集
        /// </summary>
        /// <param name="context"></param>
        /// <param name="areaCode"></param>
        private void ChangeSetSubmit(HttpContext context, string areaCode)
        {
            //验证图片是否上传
            string result = CheckImgFile(context);
            if (!string.IsNullOrEmpty(result))
            {
                OutputData("{\"Result\":false,\"Message\":\"img\",\"ReturnValue\":\"" + result + "\"}");
                return;
            }
            string corpGuid = string.Empty;
            string userName = string.Empty;
            string roleId = string.Empty;
            string changeType = string.Empty;
            string changeIds = string.Empty;
            if (context.Request.Params["changeIds"] != null)
            {
                changeIds = context.Request.Params["changeIds"].ToString();
            }
            if (context.Request.Params["corpGuid"] != null)
            {
                corpGuid = context.Request.Params["corpGuid"].ToString();
            }
            if (context.Request.Params["userName"] != null)
            {
                userName = context.Request.Params["userName"].ToString();
            }
            if (context.Request.Params["roleId"] != null)
            {
                roleId = context.Request.Params["roleId"].ToString();
            }
            if (context.Request.Params["changeType"] != null)
            {
                changeType = context.Request.Params["changeType"].ToString();
            }
            string[] changeId = changeIds.Split(',');
            using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
            {
               result = client.SubmitChange(JsonConvert.SerializeObject(changeId), changeType, corpGuid, roleId, userName, areaCode);
                OutputData(result);
            }
        }

        /// <summary>
        /// 判断图片是否上传
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string CheckImgFile(HttpContext context)
        {
            ///begin 判断图片是否上传
            if (!string.IsNullOrEmpty(context.Request.Params["funcCode"]) && !string.IsNullOrEmpty(context.Request.Params["objectId"]))
            {
                string objectId = context.Request.Params["objectId"].Trim();
                string funcCodes = context.Request.Params["funcCode"].TrimEnd(',');
                return UtilitiesTool.IsFileExists(objectId, "EF", funcCodes);
              
            }//end
            return null;
        }
        #endregion

        #region 变更审核
        /// <summary>
        /// 变更审核
        /// </summary>
        /// <param name="context"></param>
        /// <param name="areaCode"></param>
        private void ChangeAudit(HttpContext context, string areaCode)
        {
            string SetID = context.Request.Params["SetID"].ToString();
            string ddlValue = context.Request.Params["ddlValue"].ToString();
            string vierifymemo = context.Request.Params["vierifymemo"].ToString();
            string CorpUserGuid = context.Request.Params["CorpUserGuid"].ToString();
            string RoleId = context.Request.Params["RoleId"].ToString();
            string Name = context.Request.Params["Name"].ToString();
            if (string.IsNullOrWhiteSpace(SetID.ToString()))
            {
                var result1 = "{\"Result\":false,\"Message\":\"操作失败！\"}";
                OutputData(result1);
                return;
            }
            ///变更审核
            BasicService.BasicServiceClient basicService = new BasicService.BasicServiceClient();
            string operationResult = basicService.AuditChange(SetID.ToString(), ddlValue.ToString(), vierifymemo.ToString(), true, CorpUserGuid.ToString(), RoleId.ToString(), Name.ToString(), areaCode);
            if (!string.IsNullOrWhiteSpace(operationResult) && !operationResult.Equals("null"))
            {
                OperationResult opr = JsonConvert.DeserializeObject<OperationResult>(operationResult);
                string result2 = operationResult;
                //审核通过变更扫描件
                if (opr.Result && !string.IsNullOrEmpty(ddlValue) && ddlValue.Trim() == "1")
                {
                    string message = ChangeUploadImg(context);
                    if (!string.IsNullOrEmpty(message))
                    {
                        result2 = "{\"Result\":" + (opr.Result?"true":"false") + ",\"Message\":\"" + opr.Message + message + "\"}";
                    }
                }
                OutputData(result2);
                return;
            }
            OutputData("{\"Result\":false,\"Message\":\"操作失败！\"}");
        }
        /// <summary>
        /// 更新变更扫描件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string ChangeUploadImg(HttpContext context)
        {
            string sysCodes = context.Request.QueryString["sysCode"].Trim();
            string funcCodes = context.Request.QueryString["funcCode"].Trim();
            string objectId = context.Request.QueryString["objectId"].Trim();
            string funcCodeOlds = context.Request.Params["funcCodeOld"].Trim();
            if (string.IsNullOrEmpty(sysCodes) || string.IsNullOrEmpty(funcCodes) || string.IsNullOrEmpty(objectId) || string.IsNullOrEmpty(funcCodeOlds))
            {
                return string.Empty;
            }
            //取得上传文件参数
            string message = string.Empty;
            string msg = string.Empty;
            string[] sCodes = sysCodes.TrimEnd(',').Split(',');
            string[] fCodes = funcCodes.TrimEnd(',').Split(',');
            string[] fCodeOlds = funcCodeOlds.TrimEnd(',').Split(',');
            FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient();
            for (int i = 0; i < sCodes.Length; i++)
            {
                if (string.IsNullOrEmpty(sCodes[i]) || string.IsNullOrEmpty(fCodes[i]) || string.IsNullOrEmpty(fCodeOlds[i]))
                {
                    continue;
                }
                ///判断是否有上传扫描件
                if (fileService.GetFileList(objectId, sCodes[i], fCodes[i]).Count == 0)
                {
                    continue;
                }
                ///删除原文件
                DelImgFiles(objectId, sCodes[i], fCodeOlds[i]);
                ///上传新文件
                message+=UploadImages(objectId, sCodes[i], fCodes[i], fCodeOlds[i]);
                ///删除变更文件
                DelImgFiles(objectId, sCodes[i], fCodes[i]);
            }

            return message;
        }
        /// <summary>
        /// 用变更文件更新正式文件
        /// </summary>
        /// <param name="objectId"></param>
        /// <param name="sysCode"></param>
        /// <param name="funcCode"></param>
        /// <param name="funcCodeOld"></param>
        /// <returns></returns>
        private string UploadImages(string objectId, string sysCode, string funcCode, string funcCodeOld)
        {
            using (FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient())
            {
                string message = string.Empty;
                FileService.ArrayOfString files = fileService.GetFileList(objectId, sysCode, funcCode);
                foreach (var f in files)
                {
                    //取得变更扫描件
                    byte[] file = fileService.DownImageBytes(f, sysCode, funcCode);
                    if (file == null || file.Length == 0)
                    {
                        continue;
                    }
                    ////替换图片为变更后的图片，上传服务返回结果：1,上传成功！；0,错误信息
                    string result = fileService.UploadImageBytes(file, f, sysCode, funcCodeOld, true, "", "");
                    if (string.IsNullOrEmpty(result))
                    {
                        message+="扫描件"+f+"更新失败！";
                    }
                    if (!result.StartsWith("1,"))
                    {
                        message += "扫描件"+f + result.Substring(2);
                    }
                }
               
            }
            return string.Empty;
        }
        /// <summary>
        /// 删除上传图片
        /// </summary>
        /// <param name="objectId"></param>
        /// <param name="sysCode"></param>
        /// <param name="funcCode"></param>
        private string DelImgFiles(string objectId, string sysCode, string funcCode)
        {
            string message = string.Empty;
            using (FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient())
            {
                FileService.ArrayOfString files = fileService.GetFileList(objectId, sysCode, funcCode);
                foreach (var f in files)
                {
                    if (!fileService.DeleteFile(f, sysCode, funcCode))
                    {
                        message += f+",";
                    }
                }
                return message;
            }
        }
       
        #endregion
        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}